package v1

import (
	"fmt"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"ginblog/utils/validate"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

var code int

//根据username查询user
func SelectByName(c *gin.Context) {
	username := c.Param("username")
	code, data := model.SelectByName(username)
	user:= []model.User{data}
	c.JSON(http.StatusOK, gin.H {
		"code": code,
		"user": user,
		"message": errmsg.GetErrorMsg(code),
	})
}

//新增用户
func AddUser(c *gin.Context) {
	//  添加用户
	var user model.User
	err :=c.ShouldBindJSON(&user)
	fmt.Println(user)
	if err != nil {
		fmt.Println("qqqqqqqqqqqqqq", err)
	}
	fmt.Println("xxxxxxx")
	msg, code := validate.Validate(&user)
	if code != errmsg.SUCCESS {
		fmt.Println("11111")
		c.JSON(http.StatusOK, gin.H {
			"status":code,
			"message":msg,
		})
		c.Abort()
		return
	}
	code = model.CheckUser(user.Username)
	if code == errmsg.SUCCESS {
		code = model.CreateUser(&user)
		if code == errmsg.SUCCESS {
			code = errmsg.SUCCESS
		}
		if code == errmsg.ERROR {
			code = errmsg.ERROR
		}
	} else {
		code = errmsg.ERROR_USERNAME_USED
	}
	c.JSON(http.StatusOK, gin.H {
		"code":code,
		"message" : errmsg.GetErrorMsg(code),
		})
}

//查询用户列表
func GetUsers(c *gin.Context) {
	//pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	//currentPage, _ := strconv.Atoi(c.Query("currentPage"))
	users, code:= model.SelectUsers()
	c.JSON(http.StatusOK, gin.H {
		"code":code,
		"users":users,
		"message":errmsg.GetErrorMsg(code),
	})
}

//删除用户
func DeleteUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	fmt.Println("id: ", id)
	code = model.DeleteUser(id)
	c.JSON(http.StatusOK, gin.H{
		"code":code,
		"message":errmsg.GetErrorMsg(code),
	})
}

//编辑用户
func EditUser(c *gin.Context) {
	var data model.User
	id, _ := strconv.Atoi(c.Param("id"))
	err := c.ShouldBindJSON(&data)
	if err != nil {
		log.Fatal(err)
		return
	}
	//检查用户名是否重名
//	code = model.CheckUser(data.Username)
	//如果返回200，更新用户信息
//	if code == errmsg.SUCCESS {
	codeUpdate := model.Edituser(id, &data)
	if codeUpdate == errmsg.SUCCESS {
		c.JSON(http.StatusOK, gin.H {
			"code":codeUpdate,
			"message":errmsg.GetErrorMsg(codeUpdate),
		})
	}else {
		c.JSON(http.StatusOK, gin.H {
			"code":errmsg.ERROR,
			"message":errmsg.GetErrorMsg(errmsg.ERROR),
		})
	}
	//} else {
	//	c.JSON(http.StatusOK, gin.H {
	//		"code":errmsg.ERROR_USERNAME_USED,
	//		"message":errmsg.GetErrorMsg(errmsg.ERROR_USERNAME_USED),
	//	})
	//	c.Abort()
	//}

}




